export default {
  namespaced: true,
  state: {
    count: '',
    cart: JSON.parse(localStorage.cart || '[]')
  },
  mutations: {
    ADD_CART(state, payload) {
      let flag = false
      state.cart.forEach(item => {
        if (item.name === payload.name) {
          item.count += payload.count
          flag = true
        }
      })
      if (!flag) {
        state.cart.push(payload)
      }
      localStorage.cart = JSON.stringify(state.cart)
    },
    CHANGE_COUNT(state, payload) {
      state.cart.forEach(item => {
        if (item.name === payload.name) {
          item.count = payload.count
        }
      })
      localStorage.cart = JSON.stringify(state.cart)
    },
    CHANGE_CHECKED(state, payload) {
      state.cart.forEach(item => {
        if (item.name === payload.name) {
          item.checked = payload.checked
        }
      })
      localStorage.cart = JSON.stringify(state.cart)
    },
    GET_ALLCHECK(state, payload) {
      state.cart.forEach(item => {
        item.checked = payload
      })
    }
  },
  actions: {

  },
  getters: {
    getCount(state) {
      let c = 0
      state.cart.forEach(item => {
        c += item.count
      })
      return c
    },
    getCheckPrice(state) {
      let P = 0
      state.cart.forEach(item => {
        if (item.checked) {
          P += item.count * item.price
        }
      })
      return P
    },
    getAllChecked(state) {
      return state.cart.every(item => item.checked)
    }
  }
}